﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IntroduceCompany.Singleton;
using IntroduceCompany.Util;
using System.IO;


namespace IntroduceCompany.Controllers
{
    [HandleError]
    [IntroduceCompany.Models.CheckModule(ConstantClass.Backend_Order_MenuID)]
    public class OrderController : BaseController
    {
        //
        // GET: /Order/


        #region Backend

        [Authorize(Roles = ConstantClass.autOrder)]
        public ActionResult OrderList()
        {
            String orderStatusID = "";
            if (Request.Cookies[ConstantClass.cooOrderStatus] != null)
            {
                orderStatusID = Request.Cookies[ConstantClass.cooOrderStatus].Value;
            }
            ViewData["OrderStatus"] = new SelectList(DataSingleton.GetOrderModels().MakeOrderStatusList(), "orderStatusID", "orderStatusName", orderStatusID);

            return View("/Views/Backend/Order/OrderList.aspx", DataSingleton.GetOrderModels().GetOrderList(orderStatusID));
        }


        [Authorize(Roles = ConstantClass.autOrder)]
        public ActionResult ChangeDDLOrderStatus(String OrderStatusID)
        {
            if (Request.Cookies[ConstantClass.cooOrderStatus] == null)
            {
                HttpCookie cookie = new HttpCookie(ConstantClass.cooOrderStatus, OrderStatusID);
                Response.Cookies.Add(cookie);
                cookie.Expires = DateTime.Now.AddDays(ConstantClass.cooOrderStatusTimeLife);
            }
            else
            {
                Response.Cookies[ConstantClass.cooOrderStatus].Value = OrderStatusID;
            }

            return RedirectToAction("OrderList", "Order");
        }


        [Authorize(Roles = ConstantClass.autOrder)]
        public ActionResult ChangeOrderStatus(int orderID, bool status)
        {
            DataSingleton.GetOrderModels().UpdateOrderStatus(orderID, status);

            return RedirectToAction("OrderList", "Order");
        }


        [Authorize(Roles = ConstantClass.autOrder)]
        public ActionResult DeleteOrder(int orderID)
        {
            DataSingleton.GetOrderModels().DeleteOrder(orderID);
            return RedirectToAction("OrderList", "Order");
        }

        [Authorize(Roles = ConstantClass.autOrder)]
        public ActionResult OrderDetails(int orderID)
        {
            ViewData["ProductListInOrder"] = DataSingleton.GetOrderModels().GetProductListInOrder(orderID);

            return View("/Views/Backend/Order/OrderDetails.aspx", DataSingleton.GetOrderModels().GetOrderMasterDetails(orderID));
        }

        [Authorize(Roles = ConstantClass.autOrder)]
        public ActionResult CurrencyExchangeRatesEdit()
        {
            return View("/Views/Backend/Order/CurrencyExchangeRatesEdit.aspx", DataSingleton.GetOrderModels().GetCurrencyExchangeRates());
        }


        [HttpPost ,Authorize(Roles = ConstantClass.autOrder), ValidateInput(false), ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult CurrencyExchangeRatesEdit(IntroduceCompany.CurrencyExchangeRate currency)
        {
            if (ModelState.IsValid && DataSingleton.GetOrderModels().CurrencyExchangeRatesEdit(currency))
            {
                ModelState.AddModelError("NoticePage", "Tỷ giá giữa VND và USD đã được cập nhật.");
            }
            else
            {
                ModelState.AddModelError("NoticePage", "Có lỗi khi cập nhật tỷ giá giữa VND và USD.");
            }
            return View("/Views/Backend/Order/CurrencyExchangeRatesEdit.aspx", DataSingleton.GetOrderModels().GetCurrencyExchangeRates());
        }

        #endregion


//////////////////////////////////////////////////////////////////////////////////////////////////////////////

        #region Frontend

        public ActionResult ViewCart()
        {
            try
            {
                string languageID = ControllerContext.RequestContext.RouteData.Values["culture"].ToString();

                List<IntroduceCompany.Models.ProductInCart> proCartList = null;
                HttpCookie cookielist;
                if (Request.Cookies[ConstantClass.cooCart] != null)
                {
                    cookielist = Request.Cookies[ConstantClass.cooCart];
                    proCartList = DataSingleton.GetOrderModels().GetCart(cookielist, languageID);
                }

                ViewData["Cart"] = proCartList;
            }
            catch (Exception ex)
            {
                //Delete cookie if any error (Product in user cart had been deleted by admin)
                HttpCookie aCookie = Request.Cookies[ConstantClass.cooCart];
                aCookie.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(aCookie);
                ViewData["Cart"] = null;
                return Redirect(ControllerContext.HttpContext.Request.RawUrl);
            }

            return View("/Views/Frontend/Order/Cart.aspx");
        }



        public ActionResult PutProductIntoCart(String productID, String quantity)
        {

            // Get default quantity if quantity is not number and greater than 0
            int productQuantity = 1;
            int.TryParse(quantity, out productQuantity);
            if (productQuantity < 1)
            {
                productQuantity = 1;
            }

            System.Collections.Specialized.NameValueCollection cookiecoll = new System.Collections.Specialized.NameValueCollection();

            // If cookie is not existed
            if (Request.Cookies[ConstantClass.cooCart] == null ) 
            {
                cookiecoll.Add(productID, productQuantity.ToString());
                HttpCookie aCookie = new HttpCookie(ConstantClass.cooCart);
                aCookie.Expires = DateTime.Now.AddDays(ConstantClass.cooCartTimeLife);
                aCookie.Values.Add(cookiecoll);
                Response.Cookies.Add(aCookie);

            }
            // If pair key/values of cookie is existed
            else if (Request.Cookies[ConstantClass.cooCart].Values[productID] != null) 
            {
                HttpCookie aCookie = Request.Cookies[ConstantClass.cooCart];
                aCookie.Values[productID] = productQuantity.ToString();
                aCookie.Expires = DateTime.Now.AddDays(ConstantClass.cooCartTimeLife);
                Response.Cookies.Add(aCookie);
            }
            // If pair key/values of cookie is not existeds
            else 
            {
                cookiecoll.Add(productID, productQuantity.ToString());
                HttpCookie aCookie = Request.Cookies[ConstantClass.cooCart];
                aCookie.Expires = DateTime.Now.AddDays(ConstantClass.cooCartTimeLife);
                aCookie.Values.Add(cookiecoll);
                Response.Cookies.Add(aCookie);
            }

            return RedirectToAction("ViewCart", "Order");
        }


        public ActionResult DeleteOneProductInCart(String productID)
        {
            if (Request.Cookies[ConstantClass.cooCart].Values[productID] != null)
            {
                HttpCookie aCookie = Request.Cookies[ConstantClass.cooCart];
                aCookie.Values.Remove(productID);
                aCookie.Expires = DateTime.Now.AddDays(ConstantClass.cooCartTimeLife);
                Response.Cookies.Add(aCookie);
            }
            return RedirectToAction("ViewCart", "Order");
        }


        //public ActionResult DeleteCart(String url)
        //{
        //    string current_Url = ControllerContext.HttpContext.Request.RawUrl;

        //    if (Request.Cookies[ConstantClass.cooCart] != null)
        //    {
        //        HttpCookie aCookie = Request.Cookies[ConstantClass.cooCart];
        //        aCookie.Expires = DateTime.Now.AddDays(-1);
        //        Response.Cookies.Add(aCookie);
        //    }

        //    return Redirect(url);

        //}


        public String CountProductInCart()
        {
            int totalProduct = 0;
            if (Request.Cookies[ConstantClass.cooCart] != null)
            {
                if (Request.Cookies[ConstantClass.cooCart].Values[0] != null && Request.Cookies[ConstantClass.cooCart].Values[0] != "")
                {
                    totalProduct = Request.Cookies[ConstantClass.cooCart].Values.Count;
                }
            }
            return totalProduct.ToString();
        }



        public ActionResult UpdateCart(FormCollection postedForm)
        {
                HttpCookie aCookie = Request.Cookies[ConstantClass.cooCart];
                foreach (var item in postedForm)
                {
                    string productID = item.ToString();
                    string quantity = postedForm[productID].ToString();

                    int productQuantity = 1;

                    //Check product in cookie, quantity is number, quantity greater than or equal 1
                    if (Request.Cookies[ConstantClass.cooCart].Values[productID] != null && int.TryParse(quantity, out productQuantity) && productQuantity >=1)
                    {
                        aCookie.Values[productID] = productQuantity.ToString();
                    }
                }

                aCookie.Expires = DateTime.Now.AddDays(ConstantClass.cooCartTimeLife);
                Response.Cookies.Add(aCookie);


            return RedirectToAction("ViewCart", "Order");

        }


        public ActionResult CreateOrder()
        {
            return View("/Views/Frontend/Order/Order.aspx");
        }


        [HttpPost, ValidateInput(false), ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult CreateOrder(OrderMaster orderMaster)
        {
            string languageID = ControllerContext.RequestContext.RouteData.Values["culture"].ToString();

            // If cookie is existed
            if (Request.Cookies[ConstantClass.cooCart] != null)
            {
                int newOrderID = DataSingleton.GetOrderModels().CreateOrder(orderMaster, Request.Cookies[ConstantClass.cooCart], languageID);
                if (newOrderID != 0)
                {
                    ModelState.AddModelError("NoticePage", IntroduceCompany.Resources.Resx.Frontend_Order_CreateOrder_notice_Success);

                    DataSingleton.GetOrderModels().CreateAndSendMail(newOrderID);

                    //Delete cart after order
                    HttpCookie aCookie = Request.Cookies[ConstantClass.cooCart];
                    aCookie.Expires = DateTime.Now.AddDays(-1);
                    Response.Cookies.Add(aCookie);
                }
                else
                {
                    ModelState.AddModelError("NoticePage", IntroduceCompany.Resources.Resx.Frontend_Order_CreateOrder_notice_Error);
                }

            }
            else
            {
                ModelState.AddModelError("NoticePage", IntroduceCompany.Resources.Resx.Frontend_Order_CreateOrder_notice_EmpyCart);
            }

            return View("/Views/Frontend/Order/Order.aspx");
        }


        /// <summary>
        /// Return the product list page to continue buy product in cart page
        /// </summary>
        /// <returns></returns>
        public ActionResult CountinueBuyProduct()
        {
            String oldUrl = ControllerContext.HttpContext.Request.RawUrl;

            if (Request.Cookies[ConstantClass.cooUrlContinueBuyProduct] != null && Request.Cookies[ConstantClass.cooUrlContinueBuyProduct].Value != "")
            {
                return Redirect(Request.Cookies[ConstantClass.cooUrlContinueBuyProduct].Value);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }

        }

        #endregion
    }
}
